# -*- coding: utf-8 -*-

from rest_framework.decorators import action
from core.viewset import CustomModelViewSet
from core.response import JsonResponse
from .models import TestCase
from .serializers import *
from .resources import *
from .filters import *
from datetime import datetime
from .project import load_pytest_project, build_pytest_project
import os


class TestCaseViewSet(CustomModelViewSet):
    """
    测试用例管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = TestCase.objects.all()
    serializer_class = TestCaseSerializer
    filterset_class = TestCaseFilterSet
    import_resources = TestCaseImportResouces
    export_resources = TestCaseExportResouces

    @action(detail=True, methods=["GET"])
    def template(self, request, *args, **kwargs):
        py_content = f"""#!/usr/bin/env python
# -*- coding: utf-8 -*-

import yuantest

# *****************************************************
# *     SCRIPT GENERATED FROM THE TESTCASE' STEPS     *
# *          generated by yuantest platform           *
# *                {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}                *
# *****************************************************
        """
        # 动态生成测试函数
        testcase = TestCase.objects.filter(id=kwargs.get("pk")).first()
        for step in testcase.steps:
            py_content = (
                py_content
                + f"""
def test_step_{step['id']:03d}():
    # 测试步骤 {step['id']}: {step['step']}
    print("执行步骤 {step['id']}：{step['step']}")
    assert True  # 假设这里是一些验证逻辑
    
                """
            )
        py_content = (
            py_content
            + """
if __name__ == '__main__':
    main()
        """
        )
        return JsonResponse(data=py_content, msg="模板生成成功")

    @action(detail=False, methods=["POST"])
    def import_script(self, request, *args, **kwargs):
        local_path = request.data.get("path")
        product_id = request.data.get("product")
        product = Product.objects.filter(id=product_id).first()

        if not product:
            return JsonResponse(data=[], msg="产品不存在")

        if os.path.basename(local_path) != product.number.lower():
            return JsonResponse(data=[], msg="路径与产品编号不匹配")

        load_pytest_project(local_path, Product, Module, TestCase)

        return JsonResponse(data=[], msg="导入成功")

    @action(detail=False, methods=["POST"])
    def export_script(self, request, *args, **kwargs):
        local_path = request.data.pop("path")
        # 使用字典推导式来转换字典
        filters_dict = {k: v for k, v in request.data.items()}
        # 使用**操作符将字典转换为filter的参数
        testcases = TestCase.objects.filter(**filters_dict).all()
        build_pytest_project(local_path, testcases)
        return JsonResponse(data=[], msg="导出成功")
